import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, Events, IonicPage, NavController, Loading, LoadingController} from 'ionic-angular';
import {LoadingService} from "../../../services/common/loading.service";
import {ActivityStatus} from "../../../model/pages/activity/activity-filter/activity-filter.model";
import * as _ from 'lodash';
import {TeamMarketActivityFilterPage} from "../team-market-activity-filter/team-market-activity-filter";
import {TeamMarketActivityJiabaoDetailPage} from "../team-market-activity-jiabao-detail/team-market-activity-jiabao-detail";
import {TeamMarketActivityWebchatDetailPage} from "../team-market-activity-webchat-detail/team-market-activity-webchat-detail";
import {TeamMarketActivityProvider} from "../../../providers/my-team/team-market-activity/team-market-activity.provider";
import {DateService} from "../../../services/common/date.service";
import {NumberService} from "../../../services/common/number.service";
import {AdpActionSheetController} from '../../../components/common/adp-action-sheet/adp-action-sheet-controller';

@IonicPage()
@Component({
    selector: 'page-team-market-activity-list',
    templateUrl: 'team-market-activity-list.html',
    providers: [
        LoadingService,
        DateService,
        NumberService,
        TeamMarketActivityProvider]
})

export class TeamMarketActivityListPage {

    constructor(private navCtrl: NavController,
                private actionSheetCtrl: AdpActionSheetController,
                private events: Events,
                public loadCtr: LoadingController,
                public changeRef: ChangeDetectorRef,
                private teamMarketActivityProvider: TeamMarketActivityProvider,
                private dateService: DateService,
                public numberService: NumberService,
                public adpActionSheet: AdpActionSheetController,
                private loadingService: LoadingService) {
    }

    loading: Loading;
    @ViewChild(Content) content: Content;
    isScrolling = false;
    isArriveBottom = false;
    //当前试图 0代表微信获客，1代表加保活动
    private currentView = 0;
    //微信获客选择信息
    webChatGroupId: string = '';
    webChatGroupName: string = '所有组';

    //加保活动选择框信息
    jiaBaoGroupId: string = '';
    jiaBaoGroupName: string = '所有组';

    //微信获客活动列表数据
    private webChatActivityList: Array<any> = [];
    private webChatTotal = {
        join: 0,
        notJoin: 0,
        getCustomerNum: 0,
        newCustomerNum: 0
    };

    //加宝活动列表数据
    private jiaBaoActivityList: Array<any> = [];
    private jiaBaoTotal = {
        targetAgent: 0,
        targetCustomerNum: 0,
        contactVCustomerNum: 0,
        percentContact: '0'
    };

    /**
     * 附加筛选条件变量（用作展示）
     */
    private tempFilter = {
        classify: 0,
        status: [1],
        startTime: this.dateService.getCurrentMonthFirstDay(),
        endTime: this.dateService.getCurrentMonthLastDay(),
        groupId: ''
    };

    private filter={
        classify: 0,
        status: [1],
        startTime: this.dateService.getCurrentMonthFirstDay(),
        endTime: this.dateService.getCurrentMonthLastDay(),
        groupId: ''
    }
    //客户活动组名称
    chatActivityGroupTypes: Array<any> = [];
    jiaBaoActivityGroupTypes: Array<any> = [];

    ionViewDidLoad() {
        this.receiveFilterEvent();//注册监听筛选页面的事件
        this.getAllActivityInfo();
    }

    ionViewWillLeave() {
        //this.resetFilter();
    }

    /**
     * 取消订阅条件筛选
     */
    ionViewWillUnload() {
        this.events.unsubscribe('marketActivity:search');
    }

    resetFilter() {
        this.tempFilter = {
            classify: 0,
            status: [1],
            startTime: this.dateService.getCurrentMonthFirstDay(),
            endTime: this.dateService.getCurrentMonthLastDay(),
            groupId: ''
        };
    }

    getAllActivityInfo() {
        if (this.currentView === 0) {
            this.getWebActivityGroupList();
            this.getWebChatActivityList();
        } else {
            this.getJiaBaoActivityList();
            this.getJiaBaoActivityGroupList();
        }
    }

    doRefresh(refresher) {
        this.getAllActivityInfo();
        setTimeout(() => {
            refresher.complete();
        }, 1000);
    }


    webChatGroupIdChange(item) {
        this.webChatGroupId = item.groupID;
        this.filter.groupId = item.groupID;
        this.getWebChatActivityList();
    }

    jiaBaGroupIdChange(item) {
        this.jiaBaoGroupId = item.groupID;
        this.filter.groupId = item.groupID;
        this.getJiaBaoActivityList();
    }

    /*获取加宝加保活动*/
    getJiaBaoActivityList() {
        this.jiaBaoTotal = {
            targetAgent: 0,
            targetCustomerNum: 0,
            contactVCustomerNum: 0,
            percentContact: '0%'
        };
        this.loadingService.showLoading();
        this.teamMarketActivityProvider.getJiaBaoActivityList(this.filter).subscribe((res) => {
            this.jiaBaoActivityList = res;
            res.forEach((item) => {
                this.jiaBaoTotal.targetAgent += parseInt(item.targetAgent || 0);
                this.jiaBaoTotal.targetCustomerNum += parseInt(item.targetCustomerNum || 0);
                this.jiaBaoTotal.contactVCustomerNum += parseInt(item.contactVCustomerNum || 0);
                if (!item.targetCustomerNum && !item.contactVCustomerNum) {
                    item.isShowDetail = false;
                } else {
                    item.isShowDetail = true;
                }
            });

            if (this.jiaBaoTotal.targetCustomerNum != 0) {
                let temp = (this.jiaBaoTotal.contactVCustomerNum / this.jiaBaoTotal.targetCustomerNum).toFixed(2);
                this.jiaBaoTotal.percentContact = this.numberService.multiply(temp, 100) + '%';
            } else {
                this.jiaBaoTotal.percentContact = '0%';
            }
            this.loadingService.dismissLoading();
        }, () => {
            this.loadingService.dismissLoading();
        });
    }

    /**
     * 微信获客活动
     */
    getWebChatActivityList() {
        this.webChatTotal = {
            join: 0,
            notJoin: 0,
            getCustomerNum: 0,
            newCustomerNum: 0
        };
        this.loadingService.showLoading();
        this.teamMarketActivityProvider.getWebChatActivityList(this.filter).subscribe((res) => {
            res.forEach((item) => {
                this.webChatTotal.join += parseInt(item.join || 0);
                this.webChatTotal.notJoin += parseInt(item.notJoin || 0);
                this.webChatTotal.getCustomerNum += parseInt(item.getCustomerNum || 0);
                this.webChatTotal.newCustomerNum += parseInt(item.newCustomerNum || 0);

                if (!item.join && !item.notJoin && !item.getCustomerNum && !item.newCustomerNum) {
                    item.isShowDetail = false;
                } else {
                    item.isShowDetail = true;
                }
            });

            this.webChatActivityList = res;
            this.loadingService.dismissLoading();
        }, () => {
            this.loadingService.dismissLoading();
        });
    }


    openWebChatSelect() {
        let jobArray = [];

        this.chatActivityGroupTypes.forEach((item) => {
            let obj = {};
            obj['text'] = item.groupName;
            obj['cssClass'] = this.webChatGroupId == item.groupID ? 'action-sheet-selected' : '';
            obj['value'] = item.groupID;
            obj['handler'] = () => {
                this.webChatGroupName = item.groupName;
                this.webChatGroupIdChange(item);
            };
            jobArray.push(obj);
        });
        this.adpActionSheet.create({
            title: '选择组',
            buttons: jobArray,
            cssClass: 'mySelect'
        }).present();
    }

    openJiaBaoSelect() {
        let jobArray = [];
        this.jiaBaoActivityGroupTypes.forEach((item) => {
            let obj = {};
            obj['text'] = item.groupName;
            obj['cssClass'] = this.jiaBaoGroupId == item.groupID ? 'action-sheet-selected' : '';
            obj['value'] = item.groupID;
            obj['handler'] = () => {
                this.jiaBaoGroupName = item.groupName;
                this.jiaBaGroupIdChange(item);
            };
            jobArray.push(obj);
        });
        this.adpActionSheet.create({
            title: '选择组',
            buttons: jobArray,
            cssClass: 'mySelect'
        }).present();
    }

    /*获取微信获客活动列表组数据*/
    getWebActivityGroupList() {
        this.teamMarketActivityProvider.getGroupList(this.filter, 2).subscribe((res) => {
            this.chatActivityGroupTypes = [{groupID: "", groupName: "所有组"}].concat(res);
        });
    }

    /*获取加保列表组数据*/
    getJiaBaoActivityGroupList() {
        this.teamMarketActivityProvider.getGroupList(this.filter, 1).subscribe((res) => {
            this.jiaBaoActivityGroupTypes = [{groupID: "", groupName: "所有组"}].concat(res);
        });
    }

    /*跳转至微信获客运动详情页*/
    goWebChatActivityDetail(item) {
        if (!item.join && !item.notJoin && !item.getCustomerNum && !item.newCustomerNum) {
            return;
        }
        this.navCtrl.push('TeamMarketActivityWebchatDetailPage', {
            id: item.id,
            groupId: this.webChatGroupId
        })
    }

    goJiabaoActivityDetail(item) {
        if (!item.targetCustomerNum && !item.contactVCustomerNum) {
            return;
        }
        this.navCtrl.push('TeamMarketActivityJiabaoDetailPage', {
            id: item.id,
            groupId: this.jiaBaoGroupId
        })
    }

    changeCurrentView(num) {
        this.resetFilter();
        this.currentView = num;
        this.getAllActivityInfo();
    }

    receiveFilterEvent() {
        this.events.subscribe('marketActivity:search',
            (filter) => {
                this.tempFilter=  _.cloneDeep(filter);
                let cloneFilter = _.cloneDeep(filter);
                if (cloneFilter.status.length === 0) {
                    cloneFilter.status = [ActivityStatus.notStart, ActivityStatus.processing, ActivityStatus.over];
                }
                this.filter=cloneFilter;

                this.getAllActivityInfo();
            });
    }

    toFilterPage() {
        //如果点击查询，isNeedSearch=1 依旧是 this.tempFilter 真实的查询条件
        //如果没有点击，则查询条件是初始化的
        this.navCtrl.push('TeamMarketActivityFilterPage', {
            classify: this.currentView,
            filter:  _.cloneDeep(this.tempFilter)
        });
    }

    //滚动相关
    scrollStart() {
        this.isScrolling = true;
    }

    scrollEnd() {
        this.isScrolling = false;
    }

    scrolling() {
        const dimensions = this.content.getContentDimensions();
        const temp1 = dimensions.scrollHeight - dimensions.scrollTop - dimensions.contentHeight < 100;
        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }
}
